package com.yj.web.WeChat.Base;

import com.yj.web.util.HttpUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by yanlinyang on 2017/4/18.
 */
public class WxHttpDispatch {
    private final static String CharSet = "UTF-8";
    private final static String URL_FORMAT = "%s?%s";

    public static WxResponse execute(WxRequest request) throws WxException {
        WxResponse wxResponse = null;
        switch (request.getMothod()) {
            case Get:
                wxResponse = doGet(request);
                break;
            case Post:
                wxResponse = doPost(request);
                break;
            default:
                throw new WxException("undefined request method.");
        }
        if (wxResponse == null) {
            throw new WxException("response is null.");
        }
        return wxResponse;
    }

    private static WxResponse doGet(WxRequest request) throws WxException {
        String url = String.format(URL_FORMAT, request.getUrl(), constructQuery(request.getParameters()));
        return request.createResponse(HttpUtil.doGet(url));
    }

    private static WxResponse doPost(WxRequest request) throws WxException {
        String url = String.format(URL_FORMAT, request.getUrl(), constructQuery(request.getParameters()));
        return request.createResponse(HttpUtil.doPost(url, request.getBody()));
    }

    private static String constructQuery(Map<String, String> parameters) {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            for (Map.Entry<String, String> parameter : parameters.entrySet()) {
                stringBuilder.append(parameter.getKey()).append("=").append(URLEncoder.encode(parameter.getValue(), CharSet)).append("&");
            }
//            stringBuilder.append("encrypt_type=aes").append("&");
            return stringBuilder.substring(0, stringBuilder.length()-1).toString();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

/**
 * 1. gen sig: encrypt
 * 2. gen url: https://wx_api.org?encrypt_type=xxx&&msg_signature=sig
 * 3. post(url);
 * 4.
 */